<template>
  <page-meta :root-font-size="globalData.fontsize + 'px'" user-scalable="no" viewport-fit="cover" style="display: block"></page-meta>
  <view class="h100p">
    <view :style="globalData.appStyle.navStyle">
      <uni-nav-bar :height="globalData.navBarInfo.height" fixed backgroundColor="#FF7C00">
        <block slot="left">
          <uni-icons color="white" class="icon-left" @click="navigateBackPage" type="left" size="23"></uni-icons>
          <uni-icons color="white" @click="switchTabPage(`/pages/procurementPage`)" type="home" size="23"></uni-icons>
        </block>
        <block>
          <view class="leftLabel cWH">搜索信息</view>
        </block>
      </uni-nav-bar>
    </view>
    <scroll-view scroll-y :style="globalData.appStyle.contentStyle">
      <view class="box-content">
        <view class="flr fla">
          <view class="search-content flr fla">
            <uni-icons class="search-icon" type="search" size="22"></uni-icons>
            <input focus confirm-type="search" v-model="keywords" type="text" class="input" placeholder="搜索你想要找的信息" />
          </view>
          <view class="search-btn" @click="searchData">搜索</view>
        </view>
        <!-- 需求详情 -->
        <view v-if="searchResult.length === 0">
          <view class="flb fla" style="margin: 12rem 0">
            <text class="content-title">搜索历史</text>
            <view class="content-desc" @click="clearHistory()">
              <uni-icons class="search-icon" type="trash" size="12"></uni-icons>
              清空历史
            </view>
          </view>
          <view class="flw">
            <view v-for="(item, key) in needList" :key="key" class="selectd-box" @click="inserToKeyWord(item)">
              {{ item }}
            </view>
          </view>
        </view>
        <!-- 猜你喜欢 -->
        <view v-if="searchResult.length === 0" style="margin-bottom: 25%">
          <view style="margin: 12rem 0" class="content-title">猜你喜欢</view>
          <view class="flw">
            <view v-for="(item, key) in likeList" :key="key" class="selectd-box" @click="inserToKeyWord(item.categoryName)">
              {{ item.categoryName }}
            </view>
          </view>
        </view>
        <!-- 底部推荐内容 -->
        <view v-for="(item, index) in mayBeLike" :key="index" class="crad_loop_box" @click="jumpToDetail(item)">
          <view class="white_bg_box">
            <view class="ell2 card_title line-clamp-1">
              <text>{{ item.title ? item.title : item.detailInfo }}</text>
            </view>
            <view class="card_content flr">
              <view class="flr flw flex1">
                <view v-for="(label, key) in item.labels.split(',').filter(el => el) || []" :key="key" :class="key < 2 ? 'small_orange_bg_tag' : 'small_gray_bg_tag'">
                  {{ label }}
                </view>
              </view>
              <view class="fre" style="margin-right: 14rem">
                <img src="/static/img/procurement/addLike.png" class="small_icons_addLike" />
                <text>{{ item.awardQty }}</text>
              </view>
              <view class="fre">
                <img src="/static/img/procurement/watched.png" class="small_icons_watched" />
                <text>{{ item.checkQty }}</text>
              </view>
            </view>
            <view class="flcv mt15">
              <uni-icons type="location" style="margin-right: 6rem" size="15"></uni-icons>
              <text class="flex1 address_txt">{{ item.deliveryAddress }}</text>
              <view class="flcv">
                <view><uni-rate size="12" :readonly="true" v-model="item.score" /></view>
                <text class="normal_twelve_txt orange_color">{{ item.score ? item.score : 0.0 }}</text>
                <text class="normal_twelve_txt">分</text>
                <text class="normal_twelve_txt ml12 small_gary_twelve_txt">{{ formatDateTime(item.createTime, 'zh') }}</text>
                <!-- <view v-if="globalData.userInfo.id !== mayBeLike.publishUserId" class="call_phone flca">
                  <uni-icons type="phone" color="#ff7000" size="16"></uni-icons>
                  <text>拨打电话</text>
                </view> -->
              </view>
            </view>
          </view>
        </view>
      </view>
      <view v-for="(category, key) in searchResult" :key="key" class="search_result flc">
        <rich-text :nodes="category.vHtmlText"></rich-text>
        <text class="parent_label">
          <text>{{ category.parentName }}-{{ category.categoryName }}</text>
        </text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
const api = require('@/utils/request.js');
import commonMxins from '@/mixins/common.js';
export default {
  mixins: [commonMxins],
  components: {},
  data() {
    return {
      focusVisible: false,
      params: {
        pageSize: 2,
        pageNum: 1,
        timestampFlag: ''
      },
      keywords: '',
      needList: [], // 历史
      likeList: [{ categoryName: '芯片' }, { categoryName: '电子元器件' }, { categoryName: '芯片设计部门' }], // 猜你喜欢
      searchResult: [],
      mayBeLike: [],
      // 当前搜索模式 1-采购首页搜索 2-销售首页搜索 3-首页类别检索，选小类-搜的是大类
      searchMode: 1,
      eventChannel: '',
      searchUrl: ['', '/purchaseInfo/selectPagePurchaseInfo', '/saleInfo/selectPageSaleInfo', ''],
      checkUrl: ['', '/purchaseInfo/check', '/saleInfo/check', ''],
      jumpPath: ['', '/pages/procurement/detail/index?purchaseInfoId', '/pages/sale/detail/index?saleInfoId', '']
    };
  },
  onLoad(options) {
    this.getLikedCategroyInfo();
    this.searchMayBeLikeData();
    this.searchMode = options?.searchMode ?? 1;
    this.eventChannel = this.getOpenerEventChannel();
    this.needList = uni.getStorageSync('needList') ? JSON.parse(uni.getStorageSync('needList')) : [];
  },
  onShow() {},
  methods: {
    callPhone({ id }) {
      if (!this.globalData.userInfo.phoneNumber) {
        uni.navigateTo({ url: '/pages/global/authorizePhone' });
      } else {
        this.$refs.callTips.open(String(id), 2);
      }
    },
    inserToKeyWord(categoryName) {
      this.keywords = categoryName;
    },
    clearHistory() {
      this.needList = [];
    },
    // 猜你喜欢分类
    async getLikedCategroyInfo() {
      const res = await await api.request({ url: '/category/queryHotCategory', data: {}, method: 'GET' });
      this.likeList = res.data || [];
    },
    // 格式化时间展示
    formatDateTime(dateTimeString) {
      // 解析日期时间字符串
      const dateTime = new Date(dateTimeString.replace(/-/g, '/'));
      // 获取年月日时分秒.isAlreadyAward == 1
      const year = dateTime.getFullYear();
      const month = String(dateTime.getMonth() + 1).padStart(2, '0'); // getMonth() 是从0开始的，所以要+1
      const date = String(dateTime.getDate()).padStart(2, '0');
      const hours = String(dateTime.getHours()).padStart(2, '0');
      const minutes = String(dateTime.getMinutes()).padStart(2, '0');
      // 格式化为你想要的格式
      return `${month}月${date - 1}日 ${hours}:${minutes}`; // 注意：日期要减1，因为你是从2024-05-25开始，但想要5月24日
    },
    // 检索内容
    async searchMayBeLikeData() {
      const res = await api.request({ url: '/purchaseInfo/selectPagePurchaseInfo', data: { ...this.params } });
      this.mayBeLike = res.data || [];
    },
    jumpToDetail(mayBeLike) {
      //点击跳转详情
      api
        .request({ url: this.checkUrl[this.searchMode], data: { saleInfoId: mayBeLike.id }, method: 'POST' })
        .then(result => {
          uni.navigateTo({ url: `${this.jumpPath[this.searchMode]}=${mayBeLike.id}` });
        })
        .catch(err => {
          console.log(err);
        });
    },

    async searchData() {
      if (this.keywords) {
        this.needList.push(this.keywords);
        uni.setStorageSync('needList', JSON.stringify(this.needList));
        uni.navigateBack({
          delta: 1
        });
        this.eventChannel.emit('searchInfo', this.keywords);
      }
    },
    // 回退
    navigateBackPage() {
      uni.navigateBack({ delta: 1 });
    },
    switchTabPage(url) {
      uni.switchTab({ url });
    }
  }
};
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
